package com.ssm.wocket;

import com.ssm.pojo.UserInformation;
import com.ssm.utils.GetHttpSessionConfigurator;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@ServerEndpoint(value = "/timely",configurator = GetHttpSessionConfigurator.class)
public class Chat {

    public static Map<Long,Map> scoketMap = new HashMap<>();
    private Session session;
    private EndpointConfig config;


    /**
     * 发送消息
     * */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 打开scoket连接
     * @param session{Session} scoket的session
     * @param config{EndpointConfig} httpsession 配置
     * @author allan 2018/6/28
     * */
    @OnOpen
    public void onOpen(Session session,EndpointConfig config) {
        this.session = session;
        this.config = config;
        HttpSession httpSession= (HttpSession) this.config.getUserProperties().get(HttpSession.class.getName());
        UserInformation user = (UserInformation)httpSession.getAttribute("USER");
        Long id = user.getId();
        if(scoketMap.get(id) == null){
            scoketMap.put(id,new HashMap());
        };
        String  httpSessionId = httpSession.getId();
        if(scoketMap.get(id).get(httpSessionId) == null){
            scoketMap.get(id).put(httpSessionId,this);
        };
        System.out.println(user.getNickName() + "加入聊天系统");
    }
    @OnMessage
    public void onMessage(String message){
        System.out.println(message);
    }
    @OnClose
    public void onClose(){
        HttpSession httpSession= (HttpSession) this.config.getUserProperties().get(HttpSession.class.getName());
        UserInformation user = (UserInformation)httpSession.getAttribute("USER");
        String  httpSessionId = httpSession.getId();
        Long id = user.getId();
        if(scoketMap.get(id) != null){
            if(scoketMap.get(id).get(httpSessionId) != null){
                scoketMap.get(id).remove(httpSessionId);
            }
            if(scoketMap.get(id).size() == 0){
                scoketMap.remove(id);
            }
        }
        System.out.println(user.getNickName() + "退出聊天系统");
    }
    @OnError
    public void onErr(Session session, Throwable error){
        System.out.println("OnError");
    }
}
